package ejb;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.Myuser;
import model.Tag;
import model.Target;
import model.TargetTag;

/**
 * Session Bean implementation class TagFacadeEJB
 */
@Stateless

public class TagFacadeEJB implements TagFacadeEJBRemote{

	@PersistenceContext
	EntityManager em;
	
	@Override
	public boolean createTag(String tagname){
		Tag t = new Tag();
		t.setTagname(tagname);
		try{
			em.persist(t);
		}catch(Exception e){
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean ifTagExist(String tagname){
		String sql="select t from Tag t where t.tagname=:tname";
    	Query query= em.createQuery(sql);
    	query.setParameter("tname", tagname);
    	if(query.getResultList().isEmpty()){
    		return false;
    	}
    	else return true;
	}

	@Override
	public boolean ifTargetTagExist(Target t, Tag tag){
		
		String sql="select tt from TargetTag tt where tt.tagBean=:tag and tt.targetBean=:target";
    	Query query= em.createQuery(sql);
    	query.setParameter("target", t);
    	query.setParameter("tag",tag);
    	if(query.getResultList().isEmpty()){
    		return false;
    	}
    	else return true;
	}
	
	@Override
	public boolean createTargetTag(Myuser u, Target t, Tag tag){
		TargetTag tt = new TargetTag();
		tt.setMyuser(u);
		tt.setTagBean(tag);
		tt.setTargetBean(t);
		
		try{
			em.persist(tt);
		}catch(Exception e){
			e.printStackTrace();
		}
		return true;
	}
	
	@Override
	public Tag queryTagByName(String tag){
		
		Tag t = new Tag();
		try
    	{
			String sql = "select t from Tag t where t.tagname=:name";
			Query query = em.createQuery(sql);
			query.setParameter("name", tag);
			t = (Tag)query.getResultList().get(0);
	    }
    	catch (RuntimeException re)
		{
				System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
			throw re;
		}
		return t;
	}

	@Override
	public List<Tag> getTagListByTarget(Target t){
		try
    	{
			String sql = "select t.tagBean from TargetTag t where t.targetBean=:name";
			Query query = em.createQuery(sql);
			query.setParameter("name", t);
			List<Tag> result = query.getResultList();
			return result;
	    }
    	catch (RuntimeException re)
		{
				System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
			throw re;
		}
	}


}
